# -*- coding: utf-8 -*-

import json

from django.http import HttpResponse
from django.conf import settings as conf
from django.views import generic
from braces.views import JSONResponseMixin

from basic_info.models import Stock
from companies.models import QAStatisticsResult, StatisticsCategory, StatisticsOrderBy, \
                             DailyMoneyFlow, DailyMoneyFlowByIndustry, DailyMoneyFlowByConcept, \
                             RumorVerification

# 每日传闻求证

class DailyRumorVerification(generic.View):
    
    def get(self, *args, **kwargs):
        chuanwen_list = []
        date = self.request.GET.get('date', '')
        if date != '':
            daily_chuanwen = RumorVerification.objects.filter(date=date)
        if daily_chuanwen.count() == 0:
            daily_chuanwen = RumorVerification.objects.order_by('-date')[:conf.API_DEFAULT_MAX_NUM_RESULTS]

        chuanwen_list = [{'Date': chuanwen.date.strftime('%Y-%m-%d'),
                          'SecName': chuanwen.stock.short_name,
                          'Question': chuanwen.question,
                          'Answer': chuanwen.answer,
                          'Link': chuanwen.url,
                          'IsPositive': chuanwen.is_positive,
                         } for chuanwen in daily_chuanwen]

        return HttpResponse(json.dumps(chuanwen_list))
    
# 资金流数据统计结果

class DailyMoneyFlowApiView(JSONResponseMixin, generic.View):

    def get(self, *args, **kwargs):
        moneyflow_list = []
        date = self.request.GET.get('date', '')
        order = self.request.GET.get('order', '')
        group = self.request.GET.get('group', '')
        if date != '':
            order_by = 'total_flow'
            # 默认按流入降序排列
            order_prefix = '-'
            # 默认按个股分类 
            data_model = DailyMoneyFlow
            if order == 'o':
                order_prefix = ''
            if group == StatisticsCategory.INDUSTRY:
                data_model = DailyMoneyFlowByIndustry
            elif group == StatisticsCategory.CONCEPT:
                data_model = DailyMoneyFlowByConcept

            results = data_model.objects.filter(date=date).order_by(order_prefix+order_by)[:conf.API_DEFAULT_MAX_NUM_RESULTS]
            for moneyflow in results:
                if group == StatisticsCategory.INDUSTRY:
                    group_name = moneyflow.industry.name
                elif group == StatisticsCategory.CONCEPT:
                    group_name = moneyflow.concept.name
                else:
                    group_name = moneyflow.stock.short_name

                moneyflow_list.append({'GroupName': group_name,
                                       'TotalFlow': moneyflow.total_flow,
                                      })
            
        return HttpResponse(json.dumps(moneyflow_list))

# 互动问答统计结果JSON展现

class DailyQAApiView(JSONResponseMixin, generic.View):

    def get(self, *args, **kwargs):
        qa_list = []
        date = self.request.GET.get('date', '')
        category = self.request.GET.get('group', StatisticsCategory.COMPANY)
        orderby = self.request.GET.get('order', '-count')
        if date != '':
            order_by_list = orderby.split(',')
            
            results = QAStatisticsResult.objects.filter(date=date,
                                                        category=category).order_by(*order_by_list)

            qa_list = [{'count': qa.count,
                        'name': qa.name,
                        'negative_rate': qa.negative_rate,
                        'positive_rate': qa.positive_rate,
                        'polarity_count': qa.polarity_count,
                        'positive_count': qa.positive_count,
                        'negative_count': qa.negative_count,
                       } for qa in results]

        return HttpResponse(json.dumps(qa_list))

